/**
 * Copyright 2004 - 2007 Blue Bamboo International Inc. 
 *           All rights reserved.
 *
 *
 * Blue Bamboo PROPRIETARY/CONFIDENTIAL.
 *
 */

package com.bambamboo.socket.server.mina;

import java.io.FileInputStream;
import java.nio.charset.Charset;

import org.apache.commons.jelly.JellyContext;
import org.apache.commons.jelly.Script;
import org.apache.commons.jelly.XMLOutput;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.xml.sax.InputSource;

/**
 * DOCME
 * 
 * @author Nick.Tan
 * 
 */
public class DefaultIoHandler extends BaseIoHandler {

	private static Log logger = LogFactory.getLog(DefaultIoHandler.class);

	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		IoBuffer buffer = ((IoBuffer) message);

		JellyContext context = new JellyContext();
		String hexData = buffer.getHexDump();
		logger.info("HEXDATA: " + hexData);
		context.setVariable("hexData", hexData);

		Charset charset = Charset.forName("UTF-8");
		String stringData = buffer.getString(charset.newDecoder());
		logger.info("STRINGDATA: " + stringData);
		context.setVariable("stringData", stringData);

		String scriptLocation = getConfigurationBean().getScriptLocation();
		InputSource input = new InputSource(new FileInputStream(scriptLocation));
		Script script = context.compileScript(input);
		XMLOutput output = XMLOutput.createDummyXMLOutput();
		script.run(context, output);

		Object response = context.getVariable("response");
		if (response != null) {
			String resStr = response.toString();
			IoBuffer out = IoBuffer.allocate(1024);
			out.putString(resStr, charset.newEncoder());
			out.flip();
			session.write(out);
		}
	}
}
